const { User, UserType, Department } = require('../../database/index')
const { getExecutedSql } = require('../../logger');
const Sequelize = require('sequelize')


// 导出
module.exports = async (req, res) =>
{
    const operation = req.params.operation;
    const { username, password, fullname, email, pageNum, // 默认页码为1
        pageSize, phonenumber, departmentID, userTypeID, userId, sex, introduction, searchType, userTypeName, avatarUrl } = req.body
    // 计算偏移量
    const offset = (pageNum - 1) * pageSize;
    try {
        switch (operation) {
            case 'create':
                // // 根据客户端传递过来的 用户名 查询 数据库 中 是否 存在这用户名
                const model = await User.findOne({ where: { username }, attributes: { exclude: ['createdAt', 'updatedAt'] } })
                // // 判断
                if (model) {
                    res.status(400).send({
                        data: null,
                        meta: {
                            msg: "用户名已经存在！",
                            status: 400
                        }
                    })
                    return
                }
                const userData = {
                    UserName: username,
                    Password: password,
                    FullName: fullname,
                    Email: email,
                    PhoneNumber: phonenumber,
                    DepartmentID: userTypeID,
                    UserTypeID: departmentID
                }
                // 创建用户
                const data = await User.create(userData)

                // 打印sql语句
                res.status(200).send({
                    data,
                    meta: {
                        msg: "创建成功！",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            case 'read':
                // 在这里实现获取用户列表的操作
                let whereCondition = {}; // 默认查询条件为空对象
                if (searchType === "exact" && username) {
                    // 执行精确搜索
                    whereCondition = { UserName: { [Sequelize.Op.eq]: username } };
                } else if (searchType === "fuzzy" && username) {
                    // 执行模糊搜索
                    whereCondition = { UserName: { [Sequelize.Op.like]: `%${username}%` } };
                }

                const total = await User.count({ where: whereCondition }); // 根据查询条件获取数据总数

                const offset = (pageNum - 1) * pageSize; // 计算偏移量

                const userlist = await User.findAll({
                    attributes: ['UserID', 'UserName', 'FullName', 'Email', 'PhoneNumber', 'Introduction', 'Password', 'Sex', 'Avatar'],
                    include: [{ model: Department, attributes: ['DepartmentName', 'DepartmentID'] }, { model: UserType, attributes: ['UserTypeName', 'UserTypeID'] }],
                    where: whereCondition,
                    limit: Number(pageSize),
                    offset: Number(offset),
                });

                res.status(200).send({
                    data: {
                        userlist,
                        total,
                        pageSize: Number(pageSize),
                        pageNum: Number(pageNum),
                    },
                    meta: {
                        msg: '读取成功！',
                        status: 200,
                    },
                    sql: getExecutedSql(),
                });
                break;
            case 'findByName':
                console.log(username, "用户名");
                // 根据UserName来查询用户
                const user = await User.findOne(
                    {
                        where: { UserName: username },
                        include: [{ model: Department, attributes: ['DepartmentName'] }, { model: UserType, attributes: ['UserTypeName'] }]
                    },
                )
                res.status(200).send({
                    data: user,
                    meta: {
                        msg: "获取成功",
                        status: 200
                    }
                });
                break;
            case 'update':
                // 在这里实现更新用户信息的操作
                // // 判断
                const userNewData = {
                    Sex: sex,
                    FullName: fullname,
                    Password: password,
                    Introduction: introduction,
                    Email: email,
                    PhoneNumber: phonenumber,
                    UserTypeID: userTypeID,
                    DepartmentID: departmentID,
                    Avatar: avatarUrl
                }
                console.log(userId, 'userId11111111');

                // 更新用户
                const affectedRows = await User.update(userNewData, { where: { UserID: userId } });
                if (affectedRows[0] > 0) {
                    // 更新成功，根据需要获取更新后的用户信息
                    const updatedUser = await User.findOne({ where: { UserID: userId } });
                    res.status(200).send({
                        user: updatedUser,
                        meta: {
                            msg: "编辑成功！",
                            status: 201
                        },
                        sql: getExecutedSql()
                    });
                } else {
                    // 没有更新任何行，返回失败响应
                    res.status(404).send({
                        meta: {
                            msg: "未找到要更新的用户或未执行任何更新操作。",
                            status: 404
                        },
                        sql: getExecutedSql()
                    });
                }
                break;
            case 'delete':
                // 删除用户
                const deleteData = await User.destroy({ where: { UserID: userId } })
                // 打印sql语句
                res.status(200).send({
                    meta: {
                        msg: "删除成功！",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            case 'findAllName':
                const users = await User.findAll({
                    attributes: ['UserName'] // 只选择用户名字段
                });
                const userNames = users.map(user => user.UserName);
                // 打印sql语句
                res.status(200).send({
                    userNames,
                    meta: {
                        msg: "查询成功！",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            case "readAll":
                const tableData = await User.findAll({
                    attributes: ['UserID', 'FullName', 'Sex', 'UserName', 'Password', 'PhoneNumber', 'Email', 'Introduction', 'Avatar'],
                    include: [{ model: Department, attributes: ['DepartmentName', 'DepartmentID'] }, { model: UserType, attributes: ['UserTypeName', 'UserTypeID'] }],
                });

                res.status(200).send({
                    data: {
                        tableData
                    },
                    meta: {
                        msg: '读取成功！',
                        status: 200,
                    },
                    sql: getExecutedSql(),
                });
                break;
            case "findByDepartmentID":
                // 根据传入的departmentID来查找用户
                const result = await User.findAll({ where: { DepartmentID: departmentID } })
                // 打印sql语句
                res.status(200).send({
                    data: result,
                    meta: {
                        msg: "获取成功",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            case "findUserById":
                const resultByID = await User.findOne({ where: { UserID: userId } })
                res.status(200).send({
                    data: resultByID,
                    meta: {
                        msg: "获取成功",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            default:
                res.status(400).json({ message: 'Invalid operation' });
        }
    } catch (error) {
        res.status(500).json({ message: 'Internal server error', error: error.message });
    }
}